<?php

namespace app\hannel\command;

use qcloudsms\SmsMultiSender;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;

class Send extends Command
{
    protected function configure()
    {
        $this->addArgument('list_id', Argument::REQUIRED); //必传参数
        $this->setName('sendsms')->setDescription('Command Test');
    }

    protected function execute(Input $input, Output $output)
    {
        $list_id = $input->getArgument('list_id');
        $list = db('sms_lists')->find($list_id);
        if ($list && $list['status'] == 0) {
            $result = db('sms_lists')->where([
                'id' => $list_id
            ])->update([
                'status' => 1
            ]);
            if ($result) {
                $models = json_decode($list['models'], true);
                $phones = [];
                foreach ($models as $model) {
                    if($model == 'user') {
                        $lists = db($model)->distinct('mobile')->where([
                            'user_status' => ['neq',0]
                        ])->field('mobile as phone')->select();
                    }else{
                        $lists = db($model)->distinct('phone')->field('phone')->select();
                    }
                    $phone = $this->getphone($lists);
                    $phones = array_merge($phones, $phone);
                }
                $phones = array_unique($phones);
                $phone_list = [];
                foreach ($phones as $phone) {
                    $phone_list[] = $phone;
                    if (count($phone_list) == 20) {
                        $this->sendsms($phone_list, $list['templid']);
                        $phone_list = [];
                    }
                }
                if($phone_list) {
                    $this->sendsms($phone_list, $list['templid']);
                }
                $result = db('sms_lists')->where([
                    'id' => $list_id
                ])->update([
                    'status' => 2,
                    'update_time' => time()
                ]);
            }
        }
    }

    /**
     * 发送短信
     * @param $phone_list
     * @param $templid
     */
    private function sendsms($phone_list, $templid)
    {
        $multiSender = new SmsMultiSender('1400047725', 'd9c93046f4f45a7f591914ca5b506923');
        $result = $multiSender->sendWithParam("86", $phone_list, $templid, [], "", "", "");
    }

    /**
     * 获取手机号
     * @param $lists
     * @return array
     */
    private function getphone($lists)
    {
        $phone = [];
        foreach ($lists as $list) {
            $list['phone'] = trim($list['phone']);
            if (preg_match('/^1\d{10}$/', $list['phone'])) {
                $phone[] = $list['phone'];
            }
        }
        return $phone;
    }
}